package de.tum.getraenke;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;

public class DrinkService extends Service implements OnShakeListener {
	private static final String TAG = DrinkService.class.getSimpleName();
	private static final int SYNC_TIME = 60000;
	private final int SHAKE_THRESHOLD = 10;
	public static DrinkService instance;
	public static boolean paused = false;
	private ShakeSensorListener listener;
	private DrinkDBHandler dbHandler;
	private CommunicationHelper cHelper;
	public static Handler handler;
	/**
	 * called when the service is created
	 */

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(TAG, "Started service!");
		// register a shake listener
		listener = new ShakeSensorListener(this, this);
		listener.register();
		dbHandler = new DrinkDBHandler(this);
		cHelper = new CommunicationHelper();
		// easier to use this way (kind of singleton)
		instance = this;
		// start sync job periodically
		Timer timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				syncOrders();
		    	int a = 1;
		    	if(instance != null) {
		    		for(int i = 0; i <= 10; i++)
		    			a = i;
		    	}
		    	Log.d(TAG, String.valueOf(a));
			} }, 0, SYNC_TIME);
		
		return Service.START_STICKY;
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onShake(float intesity) {
		if (intesity > SHAKE_THRESHOLD) {
			PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
			if (pm.isScreenOn() && paused) {

				Intent dialogIntent = new Intent(getBaseContext(),
						AndroidGetraenkeActivity.class);
				dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				getApplication().startActivity(dialogIntent);
			}
		}
	}
	
	public void syncOrders() {
		new Thread(new Runnable () {

			@Override
			public void run() {
				Cursor c = dbHandler.getOpenOrders();
				if (c.getCount() > 0) {
					c.moveToFirst();
					while (!c.isAfterLast()) {

						HashMap<String, String> localHashMap = new HashMap<String, String>();
						localHashMap.put("gtin", c.getString(c
								.getColumnIndex(DrinkDBHandler.DRINK_GTIN)));
						localHashMap.put("amount", c.getString(c
								.getColumnIndex(DrinkDBHandler.ORDER_AMOUNT)));
						cHelper.send("bookArticleToUser", localHashMap, handler);
						if (!cHelper.getError() && cHelper.buildHashMap()) {
							Log.d(TAG, String.valueOf(cHelper.getResultInt("statusCode", 0)));
							if (cHelper.getResultInt("statusCode", 0) == 200) {
								dbHandler.completeOrderStatus(c.getInt(c
										.getColumnIndex(DrinkDBHandler.ORDER_ID)));
								Message mess = new Message();
								mess.obj = "Drink on synchronisation list was booked";
								handler.sendMessage(mess);
							}
						}
						dbHandler.updateSyncTime(c.getInt(c
								.getColumnIndex(DrinkDBHandler.ORDER_ID)));
						c.moveToNext();
					}
				}
				c.close();
				// let the service sleep
				try {
					Thread.sleep(SYNC_TIME);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
}